using System;
using System.Diagnostics;
using System.Windows.Forms;
using Christian.Helle.PocketNews.PocketPC.Controls;
using Christian.Helle.PocketNews.PocketPC.Data;
using Christian.Helle.PocketNews.PocketPC.Diagnostics;
using Microsoft.WindowsCE.Forms;

namespace Christian.Helle.PocketNews.PocketPC
{
    static class Program
    {
        [MTAThread]
        static void Main()
        {
            try
            {
                AppDomain.CurrentDomain.UnhandledException += UnhandledException;
                MobileDevice.Hibernate += Hibernate;

                if (Configuration.Initialize())
                    Application.Run(new frmMain());
            }
            finally
            {
                NotificationBalloon.Kill();
            }
        }

        static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                var handler = new DeviceExceptionHandler(ex);
                handler.HandleException("Unhandled Exception", false);

                MessageBox.Show(
                    string.Format("{0}:\n\n{1}", ex.Message, ex.StackTrace));
            }

            NotificationBalloon.Kill();
        }

        static void Hibernate(object sender, EventArgs e)
        {
            Debug.WriteLine("WM_HIBERNATE Received");

            Cache.CloseConnections();

            Cache.ArticleCollection = null;
            Cache.NewArticles = null;
        }
    }
}